import React, { Component } from 'react'
import axios from '../axi'

export default class Login extends Component {
    state = {
        username: '',
        password: '',
        data: []
    }

    getuser = async () => {
        let { data: { data } } = await axios.get('getuser')
        this.setState({ data })
    }

    login=async ()=>{
        let {username,password}=this.state
        let newdata=[...this.state.data]
        let a=newdata.some(ele=>{
            // console.log(ele.username,ele.password);
            return ele.username===username&&ele.password===password
        })
        console.log(a);
        if(a){
            let {data:{token}}=await axios.get('gettoken')
            localStorage.setItem('token',token)
            this.props.history.push('/wenji')
        }else{
            alert('用户名或密码错误')
        }
    }

    changestate=(e)=>{
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    componentDidMount(){
        this.getuser()
    }
    render() {
        let {username,password}=this.state
        return (
            <div>
                用户名:
                <input type="text" value={username} name='username' onChange={(e)=>{this.changestate(e)}}/><br />
                密码:
                <input type="text" value={password} name='password' onChange={(e)=>{this.changestate(e)}}/><br />
                <button onClick={()=>{this.login()}}>登录</button>
            </div>
        )
    }
}
